<template>
  <el-drawer :title="title" :visible.sync="drawerVisible" direction="rtl" size="67%" :before-close="handleCancel"
    custom-class="drawer-container">
    <div class="drawer-content">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="运单编号" prop="billNo">
              <el-input v-model="form.billNo" placeholder="请输入运单编号" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运单状态" prop="billStatus">
              <el-select v-model="form.billStatus" placeholder="运单状态" clearable style="width: 240px">
                <el-option v-for="dict in dict.type.bill_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 发货信息 -->
        <el-divider content-position="left">发货信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发货方" prop="senderName">
              <el-input v-model="form.senderName" placeholder="请输入发货方名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发货联系人" prop="contactA">
              <el-input v-model="form.contactA" placeholder="请输入发货联系人" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发货联系电话" prop="phoneA">
              <el-input v-model="form.phoneA" placeholder="请输入发货联系电话" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发货地址" prop="addressA">
              <el-input v-model="form.addressA" placeholder="请输入发货地址" maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="发货地点选" prop="senderProvince">
              <el-button type="primary" size="small" @click="showSenderMapPicker = true">在地图上选择</el-button>
              <span v-if="form.coordinatesA" class="ml10">
                点选坐标: {{ form.coordinatesA }}
              </span>
              <span v-if="form.senderProvince || form.senderCity || form.senderDistrict" class="ml10">
                <el-tag type="success" size="small">
                  {{ form.senderProvince || '' }} {{ form.senderCity || '' }} {{ form.senderDistrict || '' }}
                </el-tag>
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 收货信息 -->
        <el-divider content-position="left">收货信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收货方" prop="receiverName">
              <el-input v-model="form.receiverName" placeholder="请输入收货方名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货联系人" prop="contactB">
              <el-input v-model="form.contactB" placeholder="请输入收货联系人" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收货联系电话" prop="phoneB">
              <el-input v-model="form.phoneB" placeholder="请输入收货联系电话" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货地址" prop="addressB">
              <el-input v-model="form.addressB" placeholder="请输入收货地址" maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="收货地点选" prop="receiverProvince">
              <el-button type="primary" size="small" @click="showReceiverMapPicker = true">在地图上选择</el-button>
              <span v-if="form.coordinatesB" class="ml10">
                点选坐标: {{ form.coordinatesB }}
              </span>
              <span v-if="form.receiverProvince || form.receiverCity || form.receiverDistrict" class="ml10">
                <el-tag type="success" size="small">
                  {{ form.receiverProvince || '' }} {{ form.receiverCity || '' }} {{ form.receiverDistrict || '' }}
                </el-tag>
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 运输信息 -->
        <el-divider content-position="left">运输信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="货物名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入货物名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货物类型" prop="goodsType">
              <el-select v-model="form.goodsType" placeholder="请选择货物类型" style="width: 100%">
                <el-option v-for="dict in dict.type.goods_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="货物重量" prop="goodsWeight">
              <el-input-number v-model="form.goodsWeight" :precision="2" :step="0.1" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="重量单位" prop="weightUnit">
              <el-select v-model="form.weightUnit" placeholder="请选择重量单位" style="width: 100%">
                <el-option v-for="dict in dict.type.weight_unit" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货物体积(m³)" prop="volume">
              <el-input-number v-model="form.volume" :precision="3" :step="0.001" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="运输方式" prop="transportType">
              <el-select v-model="form.transportType" placeholder="运单状态" clearable style="width: 240px">
                <el-option v-for="dict in dict.type.transport_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运费(元)" prop="carriage">
              <el-input v-model="form.carriage" placeholder="请输入运费" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预计发货时间" prop="sendTime">
              <el-date-picker v-model="form.sendTime" type="date" placeholder="选择预计发货日期" value-format="yyyy-MM-dd"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计到达时间" prop="arriveTime">
              <el-date-picker v-model="form.arriveTime" type="date" placeholder="选择预计到达日期" value-format="yyyy-MM-dd"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="支付方式" prop="payType">
              <el-select v-model="form.payType" placeholder="请选择支付方式" style="width: 100%">
                <el-option v-for="dict in dict.type.pay_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 可追溯字段 -->
        <el-divider content-position="left">可追溯信息</el-divider>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="500" show-word-limit
                :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 发货地址地图选择器 -->
      <el-dialog title="选择发货地址" :visible.sync="showSenderMapPicker" width="80%" append-to-body>
        <div style="height: 500px;">
          <!-- 这里集成MapPicker组件 -->
          <MapPicker @confirm="handleSenderMapConfirm" />
        </div>
      </el-dialog>

      <!-- 收货地址地图选择器 -->
      <el-dialog title="选择收货地址" :visible.sync="showReceiverMapPicker" width="80%" append-to-body>
        <div style="height: 500px;">
          <!-- 这里集成MapPicker组件 -->
          <MapPicker @confirm="handleReceiverMapConfirm" />
        </div>
      </el-dialog>

      <div class="drawer-footer">
        <el-button type="primary" @click="submitForm">{{ title == '添加运单' ? '确 定' : '修 改' }}</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import MapPicker from '@/components/MapPicker'

export default {
  name: 'ShipmentFormDrawer',
  components: {
    MapPicker
  },
  dicts: ['bill_status', 'transport_type', 'pay_type', 'goods_type', 'weight_unit'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    form: {
      type: Object,
      required: true
    },
    rules: {
      type: Object,
      required: true
    },
    // 新增：操作模式，add-新增，edit-修改
    mode: {
      type: String,
      default: 'add'
    }
  },
  data () {
    return {
      drawerVisible: false,
      showSenderMapPicker: false,
      showReceiverMapPicker: false
    }
  },
  watch: {
    visible (val) {
      this.drawerVisible = val
    },
    drawerVisible (val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    /** 发货地址地图确认 */
    handleSenderMapConfirm (data) {
      this.form.coordinatesA = `${data.longitude},${data.latitude}`
      debugger;
      if (data.address) {
        this.form.addressA = data.address
        this.form.senderProvince = data.province
        // 处理市字段为空的情况：如果市为空，则使用省级单位地址填充
        if (!data.city || data.city.trim() === '') {
          if (data.province && data.province.trim() !== '') {
            this.form.senderCity = data.province; // 使用省级单位作为市级单位
            console.log(`发货地址市字段为空，使用省级单位填充: ${data.province}`);
          } else {
            this.form.senderCity = data.city; // 保持原值
          }
        } else {
          this.form.senderCity = data.city;
        }
        this.form.senderDistrict = data.district

        // 添加调试日志
        console.log('发货地址确认结果:', {
          province: this.form.senderProvince,
          city: this.form.senderCity,
          district: this.form.senderDistrict,
          address: this.form.addressA
        });
      }
      this.showSenderMapPicker = false
    },
    /** 收货地址地图确认 */
    handleReceiverMapConfirm (data) {
      this.form.coordinatesB = `${data.longitude},${data.latitude}`
      if (data.address) {
        this.form.addressB = data.address
        this.form.receiverLongitude = data.longitude
        this.form.receiverLatitude = data.latitude
        this.form.receiverProvince = data.province
        // 处理市字段为空的情况：如果市为空，则使用省级单位地址填充
        if (!data.city || data.city.trim() === '') {
          if (data.province && data.province.trim() !== '') {
            this.form.receiverCity = data.province; // 使用省级单位作为市级单位
            console.log(`收货地址市字段为空，使用省级单位填充: ${data.province}`);
          } else {
            this.form.receiverCity = data.city; // 保持原值
          }
        } else {
          this.form.receiverCity = data.city;
        }
        this.form.receiverDistrict = data.district

        // 添加调试日志
        console.log('收货地址确认结果:', {
          province: this.form.receiverProvince,
          city: this.form.receiverCity,
          district: this.form.receiverDistrict,
          address: this.form.addressB
        });
      }
      this.showReceiverMapPicker = false
    },
    /** 提交表单 */
    submitForm () {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 额外校验省市区信息
          if (!this.validateLocationInfo()) {
            return
          }

          // 传递操作模式给父组件
          this.$emit('submit', {
            mode: this.mode,
            data: this.form
          })
        }
      })
    },

    /** 校验省市区信息 */
    validateLocationInfo () {
      // 校验发货省市区信息
      if (!this.form.senderProvince || !this.form.senderCity || !this.form.senderDistrict) {
        this.$message.error('请在地图上选择发货地址，获取完整的省市区信息')
        return false
      }

      // 校验收货省市区信息
      if (!this.form.receiverProvince || !this.form.receiverCity || !this.form.receiverDistrict) {
        this.$message.error('请在地图上选择收货地址，获取完整的省市区信息')
        return false
      }

      return true
    },
    /** 取消按钮 */
    handleCancel () {
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped>
.drawer-content {
  padding: 20px;
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  display: flex;
  justify-content: center;
  background-color: #fff;
  border-top: 1px solid #e8e8e8;
}

.ml10 {
  margin-left: 10px;
}
</style>
